package com.sise.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sise.bean.*;
import com.sise.entity.*;
import com.sise.mapper.*;
import com.sise.service.IOrderRefundService;
import com.sise.service.IOrderService;
import com.sise.service.IProductInfoService;
import com.sise.utils.KeyUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author zj
 */
@Service
public class OrderServiceImpl implements IOrderService {

    @Resource
    private RatingMapper ratingMapper;

    @Resource
    private OrderMasterMapper orderMasterMapper;

    @Resource
    private OrderDetailMapper orderDetailMapper;

    @Resource
    private IProductInfoService productInfoService;

    @Resource
    private StoreInfoMapper storeInfoMapper;

    @Resource
    private ProductInfoMapper productInfoMapper;

    @Resource
    private ReceiverInfoMapper receiverInfoMapper;

    @Resource
    private IOrderRefundService orderRefundService;

    @Override
    public String create(OrderParameterBean orderParameterBean) {
        String orderId = KeyUtil.genUniqueKey();

        ReceiverInfo receiverInfo = receiverInfoMapper.selectById(orderParameterBean.getReceiverInfoId());

        //订单主表入库
        OrderMaster orderMaster = new OrderMaster().setOrderId(orderId)
                .setOrderEvaluateStatus(0)
                .setOrderScore(new BigDecimal(5))
                .setOpenId(orderParameterBean.getOpenId())
                .setStoreId(orderParameterBean.getStoreId())
                .setReceiverName(receiverInfo.getReceiverName())
                .setReceiverGender(receiverInfo.getReceiverGender())
                .setReceiverPhone(receiverInfo.getReceiverPhone())
                .setReceiverAddress(receiverInfo.getReceiverAddress())
                .setTotalOrderAmount(orderParameterBean.getOrderAmount())
                .setOrderStatus(0); //没有支付模块，所以提交下单就默认是待付款
        orderMasterMapper.insert(orderMaster);

        //订单详情入库
        OrderDetail orderDetail = new OrderDetail();
        List<ShoppingCartBean> shoppingCartBeanList;
        Gson gson = new Gson();
        shoppingCartBeanList = gson.fromJson(orderParameterBean.getItems(),
                new TypeToken<List<ShoppingCartBean>>() {
                }.getType());

        for (ShoppingCartBean shoppingCartBean : shoppingCartBeanList) {
            //扣商品库存
            productInfoService.decreaseStock(shoppingCartBean.getProductId(), shoppingCartBean.getProductBuyNumber());

            orderDetail.setOrderId(orderId);
            orderDetail.setOrderProductScore(5);
            orderDetail.setOrderProductEvaluateStatus(0);
            orderDetail.setProductId(shoppingCartBean.getProductId());
            orderDetail.setProductBuyNumber(shoppingCartBean.getProductBuyNumber());
            orderDetail.setProductBuyPrice(productInfoMapper.selectById(shoppingCartBean.getProductId()).getProductPrice());
            orderDetailMapper.insert(orderDetail);

            Rating rating = ratingMapper.getRatingByUserAndItem(new Rating()
                    .setUser(orderParameterBean.getOpenId()).setItem(shoppingCartBean.getProductId() + ""));
            System.out.println(orderParameterBean.getOpenId());
            System.out.println(shoppingCartBean.getProductId());
            System.out.println(ratingMapper.getRatingByUserAndItem(new Rating().setUser("oKMry5J0hJ4kUuIEU5xuhBMJR2LE").setItem("12")));
            if (rating == null) {
                Random random = new Random();
                ratingMapper.insert(new Rating().setUser(orderParameterBean.getOpenId())
                        .setItem(String.valueOf(shoppingCartBean.getProductId()))
                        .setItemRating(random.nextInt(5) + random.nextDouble() + "")
                        .setItemValue("0"));
            }
        }

        return "订单创建成功";
    }

    @Override
    public CodeMsg<List<OrderListBean>> list(String openId, String orderStatus, Integer page) {
        List<OrderListBean> orderListBeans = new ArrayList<>();

        if (openId.equals("null")) {
            return new CodeMsg<List<OrderListBean>>().setCode(401).setMsg("请登陆后再进行操作").setData(null);
        }

        QueryWrapper<OrderMaster> orderMasterWrapper = new QueryWrapper<>();
        orderMasterWrapper.eq("open_id", openId).orderByDesc("create_time");
        if (orderStatus.equals("5")) {
            orderMasterWrapper.eq("order_status", 5);
        } else if (orderStatus.equals("10")) {
            orderMasterWrapper.in("order_evaluate_status", 0, 1);
        } else {
            orderMasterWrapper.in("order_status", 0, 1, 2, 3);
        }

        Page<OrderMaster> orderMasterPage = new Page<>(page, 10);
        orderMasterPage = orderMasterMapper.selectPage(orderMasterPage, orderMasterWrapper);
        List<OrderMaster> orderMasterList = orderMasterPage.getRecords();
        if (orderMasterList.isEmpty()) {
            return new CodeMsg<List<OrderListBean>>().setCode(400).setMsg("没有搜索到你的订单").setData(null);
        }
        for (OrderMaster orderMaster : orderMasterList) {
            StoreInfo storeInfo = storeInfoMapper.selectById(orderMaster.getStoreId());

            QueryWrapper<OrderDetail> orderDetailWrapper = new QueryWrapper<>();
            orderDetailWrapper.eq("order_id", orderMaster.getOrderId());
            List<OrderDetail> orderDetailList = orderDetailMapper.selectList(orderDetailWrapper);

            OrderListBean orderListBean = new OrderListBean()
                    .setOrderEvaluateStatus(orderMaster.getOrderEvaluateStatus())
                    .setOrderMaster(orderMaster)
                    .setStoreIcon(storeInfo.getStoreIcon())
                    .setStoreName(storeInfo.getStoreName());
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            orderListBean.setCreateTime(formatter.format(orderMaster.getCreateTime()));

            List<ShoppingCartBean> shoppingCartBeanList = new ArrayList<>();
            for (OrderDetail orderDetail : orderDetailList) {
                ShoppingCartBean shoppingCartBean = new ShoppingCartBean();
                Integer ProductId = orderDetail.getProductId();
                ProductInfo productInfo = productInfoMapper.selectById(ProductId);
                shoppingCartBean.setProductName(productInfo.getProductName());
                shoppingCartBean.setProductBuyNumber(orderDetail.getProductBuyNumber());
                shoppingCartBean.setProductPrice(productInfo.getProductPrice());
                shoppingCartBeanList.add(shoppingCartBean);
            }
            orderListBean.setShoppingCartBeanList(shoppingCartBeanList);
            orderListBeans.add(orderListBean);
        }
        if (orderMasterPage.hasNext()) {
            return new CodeMsg<List<OrderListBean>>().setCode(200).setMsg("查询成功,存在下一页").setData(orderListBeans);
        } else {
            return new CodeMsg<List<OrderListBean>>().setCode(201).setMsg("查询成功，不存在下一页").setData(orderListBeans);
        }
    }

    @Override
    public OrderDetailBean detail(String orderId) {
        OrderMaster orderMaster = orderMasterMapper.selectById(orderId);

        QueryWrapper<OrderDetail> orderDetailWrapper = new QueryWrapper<>();
        orderDetailWrapper.eq("order_id", orderId);
        List<OrderDetail> orderDetailList = orderDetailMapper.selectList(orderDetailWrapper);

        OrderDetailBean orderDetailBean = new OrderDetailBean();
        orderDetailBean.setOrderId(orderMaster.getOrderId());

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        orderDetailBean.setCreateTime(formatter.format(orderMaster.getCreateTime()));
        orderDetailBean.setReceiverAddress(orderMaster.getReceiverAddress());
        orderDetailBean.setReceiverName(orderMaster.getReceiverName());
        orderDetailBean.setReceiverPhone(orderMaster.getReceiverPhone());

        List<ShoppingCartBean> shoppingCartBeanList = new ArrayList<>();
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCartBean shoppingCartBean = new ShoppingCartBean();
            Integer ProductId = orderDetail.getProductId();
            ProductInfo productInfo = productInfoMapper.selectById(ProductId);
            shoppingCartBean.setProductId(ProductId);
            shoppingCartBean.setProductIcon(productInfo.getProductIcon());
            shoppingCartBean.setProductName(productInfo.getProductName());
            shoppingCartBean.setProductBuyNumber(orderDetail.getProductBuyNumber());
            shoppingCartBean.setProductPrice(productInfo.getProductPrice());
            shoppingCartBean.setOrderProductEvaluateStatus(orderDetail.getOrderProductEvaluateStatus());
            shoppingCartBeanList.add(shoppingCartBean);
        }
        orderDetailBean.setShoppingCartBeanList(shoppingCartBeanList);
        return orderDetailBean;
    }

    @Override
    public String evaluate(String orderId, Integer productId, Integer productScore) {
        QueryWrapper<OrderDetail> orderDetailWrapper = new QueryWrapper<>();
        orderDetailWrapper.eq("order_id", orderId);
        List<OrderDetail> orderDetailList = orderDetailMapper.selectList(orderDetailWrapper);
        int evaluatedNumber = 0;    // 该订单已评价商品的数量和
        int evaluatedScore = 0;     // 该订单已评价商品的分数和
        for (OrderDetail orderDetail : orderDetailList) {
            if (orderDetail.getOrderProductEvaluateStatus().equals(1)) {
                evaluatedNumber++;
                evaluatedScore += orderDetail.getOrderProductScore();
            }
            if (orderDetail.getProductId().equals(productId)) {
                orderDetail.setOrderProductScore(productScore);
                orderDetail.setOrderProductEvaluateStatus(1);
                orderDetailMapper.updateById(orderDetail);
                evaluatedNumber++;
            }
        }
        OrderMaster orderMaster = orderMasterMapper.selectById(orderId);
        if (orderDetailList.size() == evaluatedNumber) {
            orderMaster.setOrderEvaluateStatus(2);
            // 计算订单的总分数
            orderMaster.setOrderScore(new BigDecimal(evaluatedScore).divide(new BigDecimal(evaluatedNumber)));
            orderMasterMapper.updateById(orderMaster);
        } else {
            if (orderMaster.getOrderEvaluateStatus() != 1) {
                orderMaster.setOrderEvaluateStatus(1);
                orderMasterMapper.updateById(orderMaster);
            }
        }
        return "评价商品成功";
    }

    @Override
    public CodeMsg payOrder(OrderStatusBean orderStatusBean) {
        OrderMaster orderMaster = orderMasterMapper.selectById(orderStatusBean.getOrderId());
        if (orderMaster.getOpenId().equals(orderStatusBean.getOpenId())) {
            if (orderMaster.getOrderStatus() == 0) {
                orderMaster.setOrderStatus(1);
                int tag = orderMasterMapper.updateById(orderMaster);
                if (tag == 1) {
                    return new CodeMsg().setCode(200).setMsg("支付成功");
                }
                return new CodeMsg().setCode(401).setMsg("支付失败");
            } else {
                return new CodeMsg().setCode(402).setMsg("订单状态出错");
            }
        } else {
            return new CodeMsg().setCode(400).setMsg("用户不存在");
        }
    }

    @Override
    public CodeMsg cancelOrder(OrderStatusBean orderStatusBean) {
        OrderMaster orderMaster = orderMasterMapper.selectById(orderStatusBean.getOrderId());
        if (orderMaster.getOpenId().equals(orderStatusBean.getOpenId())) {
            if (orderMaster.getOrderStatus() == 0) {
                orderMaster.setOrderStatus(4);
                int tag = orderMasterMapper.updateById(orderMaster);
                if (tag == 1) {
                    return new CodeMsg().setCode(200).setMsg("取消成功");
                }
                return new CodeMsg().setCode(401).setMsg("取消失败");
            } else {
                return new CodeMsg().setCode(402).setMsg("订单状态出错");
            }
        } else {
            return new CodeMsg().setCode(400).setMsg("用户不存在");
        }
    }

    @Override
    public CodeMsg refundOrder(OrderStatusBean orderStatusBean) {
        OrderMaster orderMaster = orderMasterMapper.selectById(orderStatusBean.getOrderId());
        if (orderMaster.getOpenId().equals(orderStatusBean.getOpenId())) {
            if (orderMaster.getOrderStatus() == 1) {
                OrderRefund orderRefund = new OrderRefund().setOrderId(orderStatusBean.getOrderId()).setRefundReason("申请退款");
                CodeMsg codeMsg = orderRefundService.applyOrderRefund(orderRefund);
                if (codeMsg.getCode() == 200) {
                    orderMaster.setOrderStatus(5);
                    int tag = orderMasterMapper.updateById(orderMaster);
                    if (tag == 1) {
                        return new CodeMsg().setCode(200).setMsg("申请成功");
                    }
                    return new CodeMsg().setCode(401).setMsg("申请失败");
                } else {
                    return new CodeMsg().setCode(403).setMsg("申请失败");
                }
            } else {
                return new CodeMsg().setCode(402).setMsg("订单状态出错");
            }
        } else {
            return new CodeMsg().setCode(400).setMsg("用户不存在");
        }
    }
}
